package com.attilax.net;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.attilax.exception.ExUtil;
import com.attilax.io.StreamUtil;
import com.attilax.io.filex;
import com.attilax.util.ResouceCloser;
//import com.csmy.my.center.util.CTUtils;
//import com.csmy.my.center.util.RequestUtil;

public class HttpUtil {
	
	public static void main(String[] args) {
		System.out.println("..");
	}
	
	/**
     * 鍚戞寚瀹歎RL鍙戦�丟ET鏂规硶鐨勮姹�
     * 
     * @param url
     *            鍙戦�佽姹傜殑URL
     * @param param
     *            璇锋眰鍙傛暟锛岃姹傚弬鏁板簲璇ユ槸 name1=value1&name2=value2 鐨勫舰寮忋��
     * @return URL 鎵�浠ｈ〃杩滅▼璧勬簮鐨勫搷搴旂粨鏋�
     */
    public static String sendGet(String url, String param) {
      
        String charset="utf-8";
        
        
        return sendGet(url, param, charset);
    }
    public static void sendGet2outStream(String url, OutputStream outStream) {
    	
        String[] a=url.split("\\?");
        if(a.length==1)
     	     sendGet2outStream(a[0], "",outStream);
        else
          sendGet2outStream(a[0], a[1],outStream);
     }
    
    public static  void sendGet2outStream(String url, String param, OutputStream outStream) {
		String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 鎵撳紑鍜孶RL涔嬮棿鐨勮繛鎺�
            URLConnection connection = realUrl.openConnection();
            // 璁剧疆閫氱敤鐨勮姹傚睘鎬�
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 寤虹珛瀹為檯鐨勮繛鎺�
            connection.connect();
            // 鑾峰彇鎵�鏈夊搷搴斿ご瀛楁
            Map<String, List<String>> map = connection.getHeaderFields();
            // 閬嶅巻鎵�鏈夌殑鍝嶅簲澶村瓧娈�
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
          
			// 瀹氫箟 BufferedReader杈撳叆娴佹潵璇诲彇URL鐨勫搷搴�
            InputStream inputStream = connection.getInputStream();
            StreamUtil.streamEx(inputStream, outStream);
			 
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
         //   e.printStackTrace();
            throw new RuntimeException(e);
        }
        // 浣跨敤finally鍧楁潵鍏抽棴杈撳叆娴�
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
              //  e2.printStackTrace();
            }
        }
      //  return result;
	}
    

	private static String sendGet(String url, String param, String charset) {
		String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 鎵撳紑鍜孶RL涔嬮棿鐨勮繛鎺�
            URLConnection connection = realUrl.openConnection();
            // 璁剧疆閫氱敤鐨勮姹傚睘鎬�
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 寤虹珛瀹為檯鐨勮繛鎺�
            connection.connect();
            // 鑾峰彇鎵�鏈夊搷搴斿ご瀛楁
            Map<String, List<String>> map = connection.getHeaderFields();
            // 閬嶅巻鎵�鏈夌殑鍝嶅簲澶村瓧娈�
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
          
			// 瀹氫箟 BufferedReader杈撳叆娴佹潵璇诲彇URL鐨勫搷搴�
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),charset));
            String line;
            while ((line = in.readLine()) != null) {
                result += line+"\r\n";
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
         //   e.printStackTrace();
            throw new RuntimeException(e);
        }
        // 浣跨敤finally鍧楁潵鍏抽棴杈撳叆娴�
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
              //  e2.printStackTrace();
            }
        }
        return result;
	}
    
    
    /**
     * 鍚戞寚瀹歎RL鍙戦�丟ET鏂规硶鐨勮姹�
     * 
     * @param url
     *            鍙戦�佽姹傜殑URL
     * @param param
     *            璇锋眰鍙傛暟锛岃姹傚弬鏁板簲璇ユ槸 name1=value1&name2=value2 鐨勫舰寮忋��
     * @return URL 鎵�浠ｈ〃杩滅▼璧勬簮鐨勫搷搴旂粨鏋�
     */
    public static String sendGet(String url) {
    	
       String[] a=url.split("\\?");
       if(a.length==1)
    	   return sendGet(a[0], "");
       else
       return sendGet(a[0], a[1]);
    }
    public static String sendGetV2(String url,String charset) {
    	url=url.trim();
        String[] a=url.split("\\?");
        if(a.length==1)
     	   return sendGet(a[0], "",charset);
        else
        return sendGet(a[0], a[1],charset);
     }
    
 

    public static String postV2(String url, String charset,
			Map<String, Object> params){
    	String postStr="";
    	if(params!=null) {
			  try {
				postStr = buildQuery(params, charset);
			} catch (IOException e) {
				ExUtil.throwExV2(e);
			}
			//out.write(postStr);
		}
    	
    	post(url, charset,postStr);
		return "";
    }

    public static String post(String url, String charset,String postSTr) {
		HttpURLConnection conn = null;
		OutputStreamWriter out = null;
		InputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader reader = null;
    	try {
    		
    		StringBuffer result = new StringBuffer();
    		 
    			conn = (HttpURLConnection) new URL(url).openConnection();
    			conn.setDoOutput(true);
    			conn.setDoInput(true);
    			conn.setRequestMethod("POST");
    			conn.setRequestProperty("accept", "*/*");
    			conn.setRequestProperty("connection", "Keep-Alive");
    			conn.setRequestProperty("Accept-Charset", charset);
    			conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    			out = new OutputStreamWriter(conn.getOutputStream(), charset);
    			out.write(postSTr);
    			out.flush();
    			inputStream = conn.getInputStream();
    			inputStreamReader = new InputStreamReader(inputStream,charset);
    			reader = new BufferedReader(inputStreamReader);
    			String tempLine = null;
    			while ((tempLine = reader.readLine()) != null) {
    				result.append(tempLine+"\r\n");
    			}
    		 
    		return result.toString();
		} catch (IOException e) {
			// TODO Auto-generated catch block
		//	e.printStackTrace();
			ExUtil.throwEx(e);
		}finally {
			new	ResouceCloser().close(out).close(reader).close(inputStreamReader).close(inputStream);
			 
		 
		}
		return "$ex";
	}
	public static String post(String url, String charset,
			Map<String, Object> params) throws IOException {
		HttpURLConnection conn = null;
		OutputStreamWriter out = null;
		InputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader reader = null;
		StringBuffer result = new StringBuffer();
		try {
			conn = (HttpURLConnection) new URL(url).openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Accept-Charset", charset);
			conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			out = new OutputStreamWriter(conn.getOutputStream(), charset);
			out.write(buildQuery(params, charset));
			out.flush();
			inputStream = conn.getInputStream();
			inputStreamReader = new InputStreamReader(inputStream);
			reader = new BufferedReader(inputStreamReader);
			String tempLine = null;
			while ((tempLine = reader.readLine()) != null) {
				result.append(tempLine);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
			if (reader != null) {
				reader.close();
			}
			if (inputStreamReader != null) {
				inputStreamReader.close();
			}
			if (inputStream != null) {
				inputStream.close();
			}
		}
		return result.toString();
	}

	public static String buildQuery(Map<String, Object> params, String charset)
			throws IOException {
		if (params == null || params.isEmpty()) {
			return null;
		}
		StringBuffer data = new StringBuffer();
		boolean flag = false;
		for (Entry<String, Object> entry : params.entrySet()) {
			if (flag) {
				data.append("&");
			} else {
				flag = true;
			}
			data.append(entry.getKey()).append("=").append(
					URLEncoder.encode(entry.getValue().toString(), charset));
		}
		return data.toString();
	}

//	public static void main(String[] args) throws Exception {
//		Map<String, Object> map = new HashMap<String, Object>();
//		String data = "[\"778564698005\",\"778564698006\"]";
//		map.put("data", data);
//		map.put("msg_type", "TRACES");
//		System.out.println(DigestUtil.digest(data, "E67D6D54AE5ED8DF31749C1EA17EEE57",DigestUtil.UTF8));
//		map.put("data_digest", DigestUtil.digest(data, "E67D6D54AE5ED8DF31749C1EA17EEE57",DigestUtil.UTF8));
//		map.put("company_id", "2464380e4f904c6f996c2f8520bcbd00");
//		try {
//			String traceString = post("http://japi.zto.cn/zto/api_utf8/traceInterface", DigestUtil.UTF8,map);
//			System.out.println(traceString);
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}
	public  static String down_test(String cabzipUrl, String savepath)
	{
		return cabzipUrl+"............"+savepath;
	}
	
	/**
	 * @author attilax 鑰佸搰鐨勭埅瀛�
	 * @since o9t 1_42_g
	 * 
	 * @param cabzip
	 * @param savepath  c:\dir\name.ext"
	 * @throws IOException
	 */
	public  static void down(String cabzipUrl, String savepath)
			 {
		
		filex.createAllPath(savepath);
		// attilax 鑰佸搰鐨勭埅瀛� 1_42_g o9t
		// 涓嬭浇缃戠粶鏂囦欢
		
try {
	
	URL url = new URL(cabzipUrl);

	URLConnection conn = url.openConnection();
	conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0");
	//((HttpsURLConnection) conn).setHostnameVerifier(new MyHostnameVerifier());
	InputStream inStream = conn.getInputStream();
	FileOutputStream fs = new FileOutputStream(savepath);

	StreamUtil.streamEx( inStream, fs);
} catch (Exception e) {
	ExUtil.throwEx(e);
}
		

	}



}